import React, { useEffect, useMemo, useState } from "react";
import { history, useLocation } from "@umijs/max";
import { Row, Col, Space, Form, Button, Tabs, Steps, Modal } from "antd";
import type { TabsProps } from 'antd';
import { fetchOrderAttachments, fetchOrderDetail, fetchOrderTracks, fetchOrderCustTracks, orderCancel } from "../services";
import './index.less';
import { orderFileTypes, orderTypes } from "@/constants/types";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { isCbmPrice, isKgsPrice, isPostCode, isTicketSettlement, isinsuranceFlag, takeToWarese } from "@/utils/dictUtil";
import { downloadFile } from "@/utils/util";
import OrderInWh from "../modals/OrderInWh";

const {Item} = Form;
type orderInfoParts = {
  orderInfo: orderTypes;
  onRefresh: any
}
type filetypes = {
  title: string;
  span: number;
  list: orderFileTypes [];
  category: string [];
}

const OrderHeader = ({orderInfo, onRefresh}: orderInfoParts) => {

  const handleReOrder = () => {
    history.push(`/order-manage/order-create?orderId=${orderInfo.id}&isReOrder=1`);
  }

  // 取消订单
  const handleOrderCancel = () => {
    Modal.confirm({
      title: "温馨提示",
      content: "是否确定取消此订单?",
      onOk: () => {
        orderCancel({id: orderInfo?.id}).then(
          res => {
            if (res?.code === '0') {
              onRefresh();
            }
          }
        )
      }
    });
  }

  const fields = [
    {
      label: '订单号',
      value: orderInfo.orderCode
    },
    {
      label: 'Shippment ID',
      value: orderInfo.shipmentId
    },
    {
      label: '订单状态',
      value: orderInfo.opStatusText
    },
    {
      label: '外部单号',
      value: orderInfo.exOrderCode
    },
    {
      label: '下单时间',
      value: orderInfo.orderTime
    },
  ];

  return (
    <div className="order-header">
      <Space size={30} style={{flexWrap: 'wrap', flex: 1, marginRight: 30}}>
        {
          fields?.map((field) => (
            <Item label={field.label} style={{marginBottom: 0}} key={field.label}>
              <strong>{field.value}</strong>
            </Item>
          ))
        }
      </Space>
      <Space>
        {orderInfo?.operations?.includes("cancel") && <Button type="primary" onClick={handleOrderCancel}>取消订单</Button>}
        <Button type="primary" onClick={handleReOrder}>再来一单</Button>
      </Space>
    </div>
  );
}

const OrderInfoCard = ({list, orderInfo}: {list: any [], orderInfo: orderTypes}) => {

  return (
    <Space direction="vertical" style={{width: '100%'}}>
      {
        list?.map(v => (
          <Item label={v.label} style={{marginBottom: 0, ...(v.style || {})}} key={v.label}>
            <strong>{v.render ? v.render(orderInfo) : orderInfo?.[v?.value]}</strong>
          </Item>
        ))
      }
    </Space>
  );
}

const InternalTrajectory = ({orderInfo}: {orderInfo: orderTypes}) => {
  const [steps, setSteps] = useState([]);

  const search = async (id: string) => {
    const res = await fetchOrderTracks({id});
    setSteps((res || []).map((v: any) => ({
      title: v?.nodeName,
      description: (
        <Space direction="vertical">
          {v?.remark && <span>备注：{v?.remark}</span>}
          <Space>
            <span>时间：{v?.trackTime}</span> 
            <span>操作人：{v?.trackBy}</span>
          </Space>
        </Space>
      )
    })));
  } 
  
  useEffect(() => {
    if (orderInfo?.id) {
      search(orderInfo?.id);
    } else{
      setSteps([]);
    }
  }, [orderInfo?.id])
  return (
    <Steps
      progressDot
      current={0}
      direction="vertical"
      items={steps}
    />
  );
}
const OuterTrajectory = ({orderInfo}: {orderInfo: orderTypes}) => {

  const [steps, setSteps] = useState([]);

  const search = async (id: string) => {
    const res = await fetchOrderCustTracks({id});
    setSteps((res || []).map((v: any) => ({
      title: v?.nodeName,
      description: (
        <Space direction="vertical">
          {v?.remark && <span>备注：{v?.remark}</span>}
          <Space>
            <span>时间：{v?.trackTime}</span> 
            <span>操作人：{v?.trackBy}</span>
          </Space>
        </Space>
      )
    })));
  } 
  
  useEffect(() => {
    if (orderInfo?.id) {
      search(orderInfo?.id);
    } else{
      setSteps([]);
    }
  }, [orderInfo?.id]);
  
  return (
    <Steps
      progressDot
      current={0}
      direction="vertical"
      items={steps}
    />
  );
}

const OrderAttachment = ({orderId}: {orderId: string | null}) => {
  const [files, setFiles] = useState<orderFileTypes []>([]);


  useEffect(() => {
    if (orderId) {
      fetchOrderAttachments({id: orderId}).then(
        res => {
          setFiles(res || []);
        }
      )
    } else {
      setFiles([]);
    }
  }, [orderId]);

  const list = useMemo(() => {
    const fileList: filetypes [] = [
      {
        title: '唛头文件',
        category: ['3','4'],
        span: 5,
        list: []
      },
      {
        title: '委托单',
        category: ['1'],
        span: 5,
        list: []
      },
      {
        title: '报关文件',
        category: ['2'],
        span: 5,
        list: []
      },
      {
        title: '入仓核实单',
        category: ['5'],
        span: 5,
        list: []
      },
      {
        title: '账单',
        category: ['6'],
        span: 4,
        list: []
      }
    ];
    files.forEach((file: orderFileTypes) => {
      fileList.forEach((v, i) => {
        if(v.category.includes(file.category)) {
          fileList[i].list.push(file);
        }
      })
    });
    return fileList;
  }, [JSON.stringify(files)])

  return (
    <div className="attchment-wrapper">
      <Row gutter={20}>
        {
          list.map((v: filetypes) => {
            return (
              <Col key={v.title} span={v.span}>
                <div>{v.title}: {v.list?.length > 0 ? '' : '无'}</div>
                <Space direction="vertical" style={{marginLeft: '-15px'}}>
                  {
                    v.list.map((file: orderFileTypes) =>  <Button key={file.path} onClick={() => downloadFile(file.path)} type="link">{file.name}</Button>)
                  }
                </Space>
              </Col>
            );
          })
        }
      </Row>
    </div>
  );
}

const OrderDetail = () => {
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const orderId = searchParams.get('orderId');

  const [orderInfo, setOrderInfo] = useState<orderTypes>({});
  // 
  const [inWhVisible, setInWhVisible] = useState(false);

  const search = () => {
    fetchOrderDetail({id: orderId}).then(
      res => {
        setOrderInfo(res || {});
      }
    )
  }

  const inWhProps = {
    title: "入仓数据",
    visible: inWhVisible,
    currentRow: {orderId},
    onCancel: () => {
      setInWhVisible(false);
    },
  }
  
  const handlePreview = () => {
    setInWhVisible(true);
  }

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '内部轨迹',
      children: (
        <div style={{paddingLeft: 100}}>
          <InternalTrajectory orderInfo={orderInfo} />
        </div>
      ),
    },
    {
      key: '2',
      label: '外部轨迹',
      children: (
        <div style={{paddingLeft: 100}}>
          <OuterTrajectory orderInfo={orderInfo} />
        </div>
      ),
    },
  ];

  const fields = [
    {
      key: '1',
      children: [
        {
          label: '客户编码',
          value: 'customerCode',
        },
        {
          label: '客户简称',
          value: 'customerName'
        },
        {
          label: '下单手机',
          value: 'mobile'
        },
        {
          label: '所属销售',
          value: 'salesName',
          style: {
            marginTop: 20
          }
        },
        {
          label: '所属客服',
          value: 'serviceName'
        },
        {
          label: '渠道',
          value: ''
        },
        {
          label: '具体渠道来源',
          value: ''
        }
      ]
    },
    {
      key: '2',
      children: [
        {
          label: '产品',
          value: 'productName',
        },
        {
          label: '国家',
          value: 'countryName'
        },
        {
          label: '起始地',
          value: 'sportName'
        },
        {
          label: '目的港',
          value: 'dportName',
        },
        {
          label: '目的地类型',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.destType} type="destType" />
        },
        {
          label: '目的地',
          render: (record: orderTypes) => {
            if (isPostCode(record?.destType)) {
              return <span>{`${record?.destCode} ${record?.destState} ${record?.destCity} ${record?.destAddress}`}</span>;
            }
            return <span>{record?.destCode}</span>
          }
        },
        {
          label: '派送方式',
          value: 'deliveryMethod'
        },
        {
          label: '开船时间',
          value: 'shipTime',
          style: {
            marginTop: 20
          }
        },
        {
          label: '截仓时间',
          value: 'cutoffTime',
        },
        {
          label: '赔付时效',
          value: 'failTimeliness',
        },
      ]
    },
    {
      key: '3',
      children: [
        {
          label: '报价方式',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.billMethod} type="paymethod" />
        },
        {
          label: '报关方式',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.bgMethod} type="customsMethod" />
        },
        {
          label: '保险',
          render: (record: orderTypes) => (
            <Space>
              <XlTableDictColumn value={record?.insuranceFlag} type="insure" />
              {isinsuranceFlag(record?.insuranceFlag) && <span>申报货值: {record?.declaredCargoValue || ''}</span>}
            </Space>
          )
        },
        {
          label: '税金',
          render: (record: orderTypes) => (
            <Space>
              <XlTableDictColumn value={record?.taxFlag} type="taxes" />
              <span>{record?.taxFee || ''}</span>
            </Space>
          )
        },
        {
          label: '结算方式',
          render: (record: orderTypes) => (
            <Space>
              <XlTableDictColumn value={record?.settlementMethod} type="settlement" />
              {/* {isMonthSettlement(record?.settlementMethod) &&  <XlTableDictColumn value={record?.payDay} type="payDay" />} */}
              {isTicketSettlement(record?.settlementMethod) &&  <XlTableDictColumn value={record?.payNode} type="payNode" />}
            </Space>
          )
        },
      ]
    },
    {
      key: '4',
      children: [
        {
          label: '提货方式',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.pickupWay} type="pickupMethod" />
        },
        {
          label: '预约时间',
          render: (record: orderTypes) => <span>{`${record?.appointPickupDate || ''} ${record?.appointPickupTime || ''}`}</span>
        },
        {
          label: '地址',
          render: (record: orderTypes) => 
          <span>{`${takeToWarese(record?.pickupWay) ? record?.cwhName || "" : [record?.pickupProvince, record?.pickupCity, record?.pickupArea, record?.pickupAddress].join('')}`}</span>
        },
        {
          label: '入仓单',
          render: (record: orderTypes) => <Button type="link" onClick={() => handlePreview()}>查看入仓数据</Button>
        },
      ]
    },
    {
      key: '5',
      children: [
        {
          label: '委托件数/箱',
          value: 'totalPieces',
        },
        {
          label: '委托总体积/CBM',
          value: 'totalVol',
        },
        {
          label: '委托总总量/KG',
          value: 'totalWeight',
        },
        {
          label: '实际件数/箱',
          value: 'inWhPieces',
          style: {
            marginTop: 20
          }
        },
        {
          label: '实际总体积/CBM',
          value: 'inWhVol',
        },
        {
          label: '实际总重量/KG',
          value: 'inWhWeight',
        },
        {
          label: '计费重/KGS',
          value: 'feeWeight',
        },
        {
          label: '计费体积/CBM',
          value: 'feeVol',
        },
        {
          label: '起收标准',
          render: (record: orderTypes) => {
            if (isKgsPrice(record?.billMethod)) {
              return <span>{record?.minTake || 0} KGS</span>
            }
            if (isCbmPrice(record?.billMethod)) {
              return <span>{record?.minTake || 0} CBM</span>
            }
            return '-';
          }
        },
      ]
    },
    {
      key: '6',
      children: [
        {
          label: '计费方式',
          render: (record: orderTypes) => <XlTableDictColumn value={record?.billMethod} type="paymethod" />
        },
        {
          label: '单价/元',
          value: 'price',
        },
        {
          label: '税金/元',
          value: 'taxFee',
        },
        {
          label: '提货费/元',
          value: 'pickupFee',
          render: (record: orderTypes) => <span>{String(record?.pickupFee) === '-1' ? '实报实销' : record?.pickupFee}</span>
        },
        {
          label: '报关费/元',
          value: 'bgFee',
        },
        {
          label: '保险/元',
          value: 'insuranceFee',
        },
        {
          label: '优惠券',
          value: 'couponName',
        },
        {
          label: '申报货值/保费元',
          render: (record: orderTypes) => {
            if (isinsuranceFlag(record?.insuranceFlag)) {
              return (
                <Space>
                  <span>{record?.declaredCargoValue}</span>/
                  <span>{record?.insuranceFee}</span>
                </Space>
              );
            }
            return '-';
          }
        },
        {
          label: "附加费",
          value: "additionalFee"
        },
        {
          label: "商检费",
          value: "cargoCheckFee"
        },
        {
          label: '总计费用/元',
          value: 'totalAmount',
        },
      ]
    }
  ];

  const onChange = () => {
    
  }


  useEffect(() => {
    if (orderId && location.pathname === '/order-manage/order-detail') {
      search()
    }
  }, [orderId])

  return (
    <>
      <OrderHeader orderInfo={orderInfo} onRefresh={search} />
      <Row style={{marginTop: 20}} gutter={20}>
        {
          fields?.map((part: any) => {

            return (
              <Col span={4} key={part.key}>
                <OrderInfoCard list={part.children} orderInfo={orderInfo} />
              </Col>
            );
          })
        }
      </Row>
      {
        orderInfo?.remark && (
          <div style={{marginTop: 20}}>备注：<strong>{orderInfo?.remark}</strong></div>
        )
      }
      <OrderAttachment orderId={orderId} />
      <div style={{marginTop: 20}}>
        <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
      </div>
      {inWhVisible && <OrderInWh {...inWhProps} />}
    </>
  );
}
export default OrderDetail;